<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>英雄管理</title>
    <link href="../css/quill.snow.css" rel="stylesheet">
    <script src="../js/quill.js"></script>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            padding: 20px;
            background: white;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .add-btn {
            background: #8b0000;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        .hero-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        .hero-card {
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 10px;
            text-align: center;
            position: relative;
        }

        .hero-image {
            width: 120px;
            height: 150px;
            object-fit: cover;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .hero-actions {
            margin-top: 10px;
        }

        .btn {
            padding: 5px 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 5px;
        }

        .btn-edit {
            background: #4caf50;
            color: white;
        }

        .btn-delete {
            background: #f44336;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 800px;
            max-height: 95vh;
            overflow-y: auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        /* 添加编辑器容器样式 */
        #editor-container {
            height: calc(70vh - 100px);
            margin-bottom: 20px;
            min-height: 400px;
        }
        
        /* 编辑器内容区域样式 */
        .ql-container {
            height: calc(100% - 42px) !important;  /* 减去工具栏的高度 */
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .form-group textarea {
            height: 100px;
            resize: vertical;
        }

        .image-preview {
            width: 120px;
            height: 150px;
            border: 2px dashed #ddd;
            margin: 10px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            background: #f5f5f5;
        }

        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
            display: block;
        }

        .image-preview:hover::after {
            content: '点击更换图片';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .no-data {
            text-align: center;
            color: #999;
            padding: 40px 0;
            font-size: 14px;
            width: 100%;
            background: rgba(0,0,0,0.02);
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h2>英雄管理</h2>
        <button class="add-btn" onclick="showAddModal()">添加英雄</button>
    </div>

    <div class="hero-list" id="heroList">
        <!-- 英雄列表将通过 JavaScript 动态加载 -->
    </div>

    <!-- 添加/编辑模态框 -->
    <div id="heroModal" class="modal">
        <div class="modal-content">
            <h3 id="modalTitle">添加英雄</h3>
            <form id="heroForm" onsubmit="saveHero(event)">
                <input type="hidden" id="heroId">
                
                <div class="form-group">
                    <label>英雄姓名</label>
                    <input type="text" id="heroName" required>
                </div>

                <div class="form-group">
                    <label>排序（数字越大越靠前）</label>
                    <input type="number" id="heroSort" min="0" value="0" required>
                </div>

                <div class="form-group">
                    <label>英雄照片</label>
                    <div class="image-preview" onclick="document.getElementById('imageInput').click()">
                        <img id="imagePreview" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='150' viewBox='0 0 120 150'%3E%3Crect width='120' height='150' fill='%23ddd'/%3E%3Ctext x='50%25' y='50%25' text-anchor='middle' dy='.3em' fill='%23666' font-size='14'%3E点击上传%3C/text%3E%3C/svg%3E" alt="预览图">
                    </div>
                    <input type="file" id="imageInput" accept="image/*" style="display: none" onchange="handleImageUpload(event)">
                    <input type="hidden" id="heroImage" required>
                </div>

                <div class="form-group">
                    <label>英雄事迹</label>
                    <div id="editor-container"></div>
                    <input type="hidden" id="heroDescription" required>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-save">保存</button>
                    <button type="button" class="btn" onclick="closeModal()">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let editor = null;

        // 加载英雄列表
        async function loadHeroes() {
            try {
                const response = await fetch('../api/heroes/list.php');
                const result = await response.json();
                
                if (!result.success) throw new Error(result.message);
                
                const heroes = result.data;
                // 按 sort 字段排序
                heroes.sort((a, b) => b.sort - a.sort);
                
                const heroList = document.getElementById('heroList');
                if (heroes.length === 0) {
                    heroList.innerHTML = '<div class="no-data">暂无英雄数据</div>';
                    return;
                }
                
                heroList.innerHTML = heroes.map(hero => `
                    <div class="hero-card">
                        <img src="${hero.image}" alt="${hero.name}" class="hero-image">
                        <div class="hero-name">${hero.name}</div>
                        <div class="hero-actions">
                            <button class="btn btn-edit" onclick='editHero(${JSON.stringify(hero)})'>编辑</button>
                            <button class="btn btn-delete" onclick="deleteHero(${hero.id})">删除</button>
                        </div>
                    </div>
                `).join('');
            } catch (error) {
                console.error('加载失败:', error);
                alert('加载失败，请重试');
            }
        }

        // 创建编辑器
        function initEditor() {
            const editorConfig = {
                theme: 'snow',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline', 'strike'],
                        ['blockquote', 'code-block'],
                        [{ 'header': 1 }, { 'header': 2 }],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        [{ 'indent': '-1'}, { 'indent': '+1' }],
                        [{ 'size': ['small', false, 'large', 'huge'] }],
                        [{ 'color': [] }, { 'background': [] }],
                        ['link', 'image'],
                        ['clean']
                    ]
                },
                placeholder: '请输入英雄事迹...'
            };

            editor = new Quill('#editor-container', editorConfig);

            // 监听内容变化
            editor.on('text-change', function() {
                const content = editor.root.innerHTML;
                document.getElementById('heroDescription').value = 
                    content === '<p><br></p>' ? '' : content;
            });
        }

        // 处理图片上传
        async function handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            try {
                const formData = new FormData();
                formData.append('image', file);

                const response = await fetch('../api/heroes/upload.php', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (!result.success) {
                    throw new Error(result.message || '服务器返回错误');
                }

                // 更新预览图和隐藏输入框
                document.getElementById('imagePreview').src = result.url;
                document.getElementById('heroImage').value = result.url;
            } catch (error) {
                console.error('上传失败:', error);
                let errorMessage = '图片上传失败: ';
                
                // 如果是网络错误
                if (error.name === 'TypeError') {
                    errorMessage += '网络错误，请检查网络连接';
                } 
                // 如果是服务器返回的错误信息
                else if (error.message) {
                    errorMessage += error.message;
                } 
                // 其他未知错误
                else {
                    errorMessage += '未知错误，请重试';
                }
                
                alert(errorMessage);
            }
        }

        // 修改显示添加模态框函数
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加英雄';
            document.getElementById('heroId').value = '';
            document.getElementById('heroForm').reset();
            document.getElementById('imagePreview').src = 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'120\' height=\'150\' viewBox=\'0 0 120 150\'%3E%3Crect width=\'120\' height=\'150\' fill=\'%23ddd\'/%3E%3Ctext x=\'50%25\' y=\'50%25\' text-anchor=\'middle\' dy=\'.3em\' fill=\'%23666\' font-size=\'14\'%3E点击上传%3C/text%3E%3C/svg%3E';
            
            document.getElementById('heroModal').style.display = 'flex';
            
            // 确保编辑器已初始化
            if (!editor) {
                initEditor();
            }
            editor.root.innerHTML = '';
        }

        // 修改显示编辑模态框函数
        function editHero(hero) {
            document.getElementById('modalTitle').textContent = '编辑英雄';
            document.getElementById('heroId').value = hero.id;
            document.getElementById('heroName').value = hero.name;
            document.getElementById('imagePreview').src = hero.image;
            document.getElementById('heroImage').value = hero.image;
            document.getElementById('heroSort').value = hero.sort || 0;
            
            document.getElementById('heroModal').style.display = 'flex';
            
            // 确保编辑器已初始化
            if (!editor) {
                initEditor();
            }
            editor.root.innerHTML = hero.description || '';
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('heroModal').style.display = 'none';
        }

        // 保存英雄信息
        async function saveHero(event) {
            event.preventDefault();
            
            try {
                const content = editor.root.innerHTML;
                const description = content === '<p><br></p>' ? '' : content;
                
                const heroData = {
                    name: document.getElementById('heroName').value,
                    image: document.getElementById('heroImage').value,
                    description: description,
                    sort: parseInt(document.getElementById('heroSort').value)
                };

                const id = document.getElementById('heroId').value;
                if (id) {
                    heroData.id = parseInt(id);
                }

                console.log('Saving hero:', heroData); // 添加调试日志

                const response = await fetch(`../api/heroes/${id ? 'update' : 'add'}.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(heroData)
                });
 
                console.log('Response status:', response.status); // 添加调试日志
                
                const result = await response.json();
                console.log('Response data:', result); // 添加调试日志

                if (!result.success) throw new Error(result.message || '保存失败');

                closeModal();
                loadHeroes();
            } catch (error) {
                console.error('保存失败:', error);
                alert('保存失败，请重试: ' + error.message);
            }
        }

        // 删除英雄
        async function deleteHero(id) {
            if (!confirm('确定要删除这位英雄吗？')) return;

            try {
                const response = await fetch(`../api/heroes/delete.php?id=${id}`);
                const result = await response.json();
                if (!result.success) throw new Error(result.message);

                loadHeroes();
            } catch (error) {
                console.error('删除失败:', error);
                alert('删除失败，请重试');
            }
        }

        // 页面加载时加载英雄列表
        window.onload = function() {
            // 初始加载英雄列表
            loadHeroes();
        }

        // 点击模态框背景关闭
        document.getElementById('heroModal').addEventListener('click', (e) => {
            if (e.target.id === 'heroModal') {
                closeModal();
            }
        });
    </script>
</body>
</html> 